package scatter.interview.rest.interview.i3_thread;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * cas 原子性
 * Created by yangwei
 * Created at 2020/12/3 15:32
 */

public class IplusCas extends Thread{
    public static AtomicInteger a = new AtomicInteger(0);

    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            //线程1：取出a的值a=0(被暂停)
            a.getAndIncrement();
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //写回
        }
        System.out.println("修改完毕！a=" + a);
    }
    public static void main(String[] args) throws InterruptedException {
        //1.启动两个线程
        IplusCas t1 = new IplusCas();
        IplusCas t2 = new IplusCas();
        t1.start();
        t2.start();
        Thread.sleep(1000);
        System.out.println("获取a最终值：" + IplusCas.a);
    }
}
